package org.itboys.admin.service.lasted;

import org.itboys.admin.entity.lasted.SystemRole;
import org.itboys.admin.entity.lasted.SystemUserRole;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年2月27日
 * 联系方式 ：empty90911@126.com
 * 描述：系统_用户角色关联表_Service，江雄重新写的
 */
@Service
public class SystemUserRoleService extends BaseMongoService<SystemUserRole> {
   /* @Autowired
    private SystemUserService userService;*/
    @Autowired
    private SystemRoleService roleService;




    @Resource(name = "adminDS")
    private MongoDataSource ds;

    @Override
    protected MongoDataSource getMongoDataSource() {
        return ds;
    }

    @Override
    protected Class<SystemUserRole> getEntityClass() {
        return SystemUserRole.class;
    }

    /**
     * 保存用户角色
     * @param userId
     * @param roleIds
     */
    public void saveUserRoles(Long userId,List<Long> roleIds){
        //删除原来的数据
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("userId",userId);
        super.doDelete(param);
        //新增本次的
        if(ListUtil.isNotNull(roleIds)){
            List<SystemUserRole> userRoles = new ArrayList<SystemUserRole>();
            for(Long roleId:roleIds){
                SystemUserRole userRole = new SystemUserRole(userId,roleId);
                userRoles.add(userRole);
            }
            super.batchSave(userRoles);
        }
    }

    /**
     * 分配用户角色，且勾选用户已经有的角色
     * @param userId
     */
    public List<Map<String,Object>> allotUserRole(Long userId){
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        Map<String,Object> param = new HashMap<String,Object>();
        //所有角色
        List<SystemRole> roles = roleService.list(param);
        //用户角色
        param.clear();
        param.put("userId",userId);
        List<SystemUserRole> userRoles=super.list(param);
        for(SystemRole role:roles){
            Map<String,Object> result = new HashMap<String,Object>();
            result.put("id",role.getId());
            result.put("name",role.getName());
            result.put("checked",false);
            for(SystemUserRole userRole:userRoles){
                   if(LongUtil.isNotZreo(userRole.getRoleId())&&
                           role.getId()==userRole.getRoleId().longValue()){

                       result.put("checked",true);
                       break;
                   }
            }
            results.add(result);
        }
        return results;
    }


}
